package com.uhylab.uhuvinetest.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.uhylab.uhuvinetest.DaoInset;
import com.uhylab.uhuvinetest.JNIJson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.History_Content;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.LocalHistory;
import com.uhylab.uhuvinetest.dao.LocalHistoryDao;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 *
 * */
public class UHU2ResultActivity extends UHBaseActivity implements View.OnClickListener {

    private ImageView register_back;
    private ImageView item_img0,item_img1,item_img2,item_img3;
    private TextView item_cotent0,item_cotent1,item_cotent2,item_cotent3;

    //准备上传服务器数据
    ArrayList<History_Content> arrayList = new ArrayList<>();

    private float[] floats;
    //伪造的floatss
    private float[] floatss = new float[11];

    private VolleySingleton volleySingleton;
    private LocalHistoryDao localHistoryDao;
    private String colorSetion[] = {
            "leukocytes_status", "nitrite_status", "urobilinogen_status", "protein_status",
            "ph_status", "blood_status",
            "gravity_status", "ketones_status", "bilirubin_status", "glucose_status", "ascorbicacid_status"
    };

    private String t;


    @Override
    public int bindLayout() {
        return R.layout.activity_uhu2_result;
    }

    @Override
    public void initView(View view) {
        Intent intent = getIntent();
        //得到上一个界面进来的H值
        floats = intent.getExtras().getFloatArray("floats");
        for (int i = 0; i < floats.length; i++) {
            floatss[i] = floats[i];
        }
        for (int i = 4; i < 11; i++) {
            floatss[0] = -1;
        }

        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        localHistoryDao = DaoSingleton.getInstance().getLocalHistoryDao();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        t = format.format(new Date());

        register_back = (ImageView) findViewById(R.id.register_back);

        item_img0 = (ImageView) findViewById(R.id.item_img0);
        item_img1 = (ImageView) findViewById(R.id.item_img1);
        item_img2 = (ImageView) findViewById(R.id.item_img2);
        item_img3 = (ImageView) findViewById(R.id.item_img3);

        item_cotent0 = (TextView) findViewById(R.id.item_cotent0);
        item_cotent1 = (TextView) findViewById(R.id.item_cotent1);
        item_cotent2 = (TextView) findViewById(R.id.item_cotent2);
        item_cotent3 = (TextView) findViewById(R.id.item_cotent3);

        register_back.setOnClickListener(this);

    }

    @Override
    public void doBusiness(Context mContext) {
        JNIJson jniJson = new JNIJson(UHU2ResultActivity.this);
        final String[] states = {
                jniJson.getLeukocytes().get(get_near(jniJson.getS(), floats[0])).getState(),
                jniJson.getNitrite().get(get_near(jniJson.getNis(), floats[1])).getState(),
                jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), floats[2])).getState(),
                jniJson.getProtein().get(get_near(jniJson.getPrs(), floats[3])).getState(),
                "null",
                "null",
                "null",
                "null",
                "null",
                "null",
                "null"
        };

        if (states[0].equals("正常")) {
            item_img0.setImageResource(R.drawable.history_health);
        } else if (states[0].equals("轻微")) {
            item_img0.setImageResource(R.drawable.history_bad);
        } else if (states[0].equals("严重")) {
            item_img0.setImageResource(R.drawable.history_dangerous);
        } else if (states[0].equals("微量")) {
            item_img0.setImageResource(R.drawable.history_health1);
        }

        if (states[1].equals("正常")) {
            item_img1.setImageResource(R.drawable.history_health);
        } else if (states[1].equals("轻微")) {
            item_img1.setImageResource(R.drawable.history_bad);
        } else if (states[1].equals("严重")) {
            item_img1.setImageResource(R.drawable.history_dangerous);
        } else if (states[1].equals("微量")) {
            item_img1.setImageResource(R.drawable.history_health1);
        }

        if (states[2].equals("正常")) {
            item_img2.setImageResource(R.drawable.history_health);
        } else if (states[2].equals("轻微")) {
            item_img2.setImageResource(R.drawable.history_bad);
        } else if (states[2].equals("严重")) {
            item_img2.setImageResource(R.drawable.history_dangerous);
        } else if (states[2].equals("微量")) {
            item_img2.setImageResource(R.drawable.history_health1);
        }

        if (states[3].equals("正常")) {
            item_img3.setImageResource(R.drawable.history_health);
        } else if (states[3].equals("轻微")) {
            item_img3.setImageResource(R.drawable.history_bad);
        } else if (states[3].equals("严重")) {
            item_img3.setImageResource(R.drawable.history_dangerous);
        } else if (states[3].equals("微量")) {
            item_img3.setImageResource(R.drawable.history_health1);
        }


        final String[] contents = {
                jniJson.getLeukocytes().get(get_near(jniJson.getS(), floats[0])).getContentValue()
                        + "" + jniJson.getLeukocytes().get(get_near(jniJson.getS(), floats[0])).getUnit(),
                jniJson.getNitrite().get(get_near(jniJson.getNis(), floats[1])).getContentValue()
                        + "" + jniJson.getNitrite().get(get_near(jniJson.getNis(), floats[1])).getUnit(),
                jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), floats[2])).getContentValue() + ""
                        + jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), floats[2])).getUnit(),
                jniJson.getProtein().get(get_near(jniJson.getPrs(), floats[3])).getContentValue() + "" +
                        jniJson.getProtein().get(get_near(jniJson.getPrs(), floats[3])).getUnit(),
                "null",
                "null",
                "null",
                "null",
                "null",
                "null",
                "null"
        };

        item_cotent0.setText(contents[0]);
        item_cotent1.setText(contents[1]);
        item_cotent2.setText(contents[2]);
        item_cotent3.setText(contents[3]);

        initRequest(floatss,states);

    }

    @Override
    public void resume() {

    }

    @Override
    public void destroy() {

    }

    public float GRB2H(int R, int G, int B) {

        float H, S, V;

        int max = Math.max(R, Math.max(G, B));
        int min = Math.min(R, Math.min(G, B));
        int Delta = max - min;

        if (max == 0) {
            S = (float) 0.0;
        } else {
            S = (float) Delta / max;
        }

        if (max == R) {
            H = 60 * (G - B) / Delta;
        } else if (max == G) {
            H = 120 + 60 * (B - R) / Delta;
        } else {
            H = 240 + 60 * (R - G) / Delta;
        }

        if (H < 0.0) {
            H = 360 + H;
        } else if (H > 360.0) {
            H -= 360;
        }

        return H;
    }

    public static int get_near(float[] array, float target) {
        if (array.length == 0) return -1;
        if (array.length == 1) return 0;
        float[] floa = new float[array.length];
        for (int k = 0; k < floa.length; k++) {
            floa[k] = array[k];
        }
        Arrays.sort(array);
        int min = 0;
        int max = array.length - 1;
        int mid = (min + max) / 2;

        while (max - min > 1) {
            if (target == array[mid]) return mid;
            if (target < array[mid]) max = mid;
            if (target > array[mid]) min = mid;
            mid = (min + max) / 2;
        }

        for (int j = 0; j < floa.length; j++) {
            if (floa[j] == array[array[max] - target < target - array[min] ? max : min]) {
                return j;
            }
        }
        return (array[max] - target) < (target - array[min]) ? max : min;
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_back:
                finish();
                break;
        }
    }

//    private void initRequest(final float[] lists, final String[] daoInsets) {
//        StringRequest request = new StringRequest(Request.Method.POST, UHBase.insertHistory, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
//                DaoInset daoInset = new DaoInset(lists, daoInsets, t, tel);
//                LocalHistory start = daoInset.start();
//                localHistoryDao.insertOrReplace(start);
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
//                for (int i = 0; i < colorSetion.length; i++) {
//                    if (i >= 4) {
//                        params.put(colorSetion[i], "-1");
//                        continue;
//                    }
//                    if (daoInsets[i].equals("正常")) {
//                        params.put(colorSetion[i], "0");
//                    } else if (daoInsets[i].equals("轻微")) {
//                        params.put(colorSetion[i], "1");
//                    } else if (daoInsets[i].equals("严重")) {
//                        params.put(colorSetion[i], "2");
//                    } else if (daoInsets[i].equals("微量")) {
//                        params.put(colorSetion[i], "3");
//                    }
//                }
//                params.put("telephone", tel);
//                params.put("leukocytes", String.valueOf(lists[0]));
//                params.put("nitrite", String.valueOf(lists[1]));
//                params.put("urobilinogen", String.valueOf(lists[2]));
//                params.put("protein", String.valueOf(lists[3]));
//                params.put("ph", String.valueOf(lists[4]));
//                params.put("blood", String.valueOf(lists[5]));
//                params.put("gravity", String.valueOf(lists[6]));
//                params.put("ketones", String.valueOf(lists[7]));
//                params.put("bilirubin", String.valueOf(lists[8]));
//                params.put("glucose", String.valueOf(lists[9]));
//                params.put("ascorbicacid", String.valueOf(lists[10]));
//                params.put("date", t);
//                return params;
//            }
//        };
//
//        if (!SharedPreUtils.getString(getApplication(), "user_tel", "").equals("")) {
//            volleySingleton.addQueue(request, "insertHistory");
//        }
//    }



    private void initRequest(final float[] lists, final String[] daoInsets) {
        String userToken = SharedPreUtils.getString(this, "user_token", null);
        JSONObject jsonObject = new JSONObject();
        try {

            for (int i = 0; i < colorSetion.length; i++) {
                if (i >= 4) {
                    jsonObject.put(colorSetion[i], "-1");
                    continue;
                }

                if (daoInsets[i].equals("正常")) {
                    jsonObject.put(colorSetion[i], "0");
                } else if (daoInsets[i].equals("轻微")) {
                    jsonObject.put(colorSetion[i], "1");
                } else if (daoInsets[i].equals("严重")) {
                    jsonObject.put(colorSetion[i], "2");
                } else if (daoInsets[i].equals("微量")) {
                    jsonObject.put(colorSetion[i], "3");
                }
            }
            jsonObject.put("leukocytes", String.valueOf(lists[0]));
            jsonObject.put("nitrite", String.valueOf(lists[1]));
            jsonObject.put("urobilinogen", String.valueOf(lists[2]));
            jsonObject.put("protein", String.valueOf(lists[3]));
            jsonObject.put("ph", String.valueOf(lists[4]));
            jsonObject.put("blood", String.valueOf(lists[5]));
            jsonObject.put("gravity", String.valueOf(lists[6]));
            jsonObject.put("ketones", String.valueOf(lists[7]));
            jsonObject.put("bilirubin", String.valueOf(lists[8]));
            jsonObject.put("glucose", String.valueOf(lists[9]));
            jsonObject.put("ascorbicacid", String.valueOf(lists[10]));
            jsonObject.put("date", t);

            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UHBase.newInsertHistory
                    + "token=" + userToken
                    , jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
//                    Log.e("ResultActivity", "response:" + response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
                    DaoInset daoInset = new DaoInset(lists, daoInsets, t, tel);
                    LocalHistory start = daoInset.start();
                    localHistoryDao.insertOrReplace(start);
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Accept", "application/json");
                    headers.put("Content-Type", "application/json; charset=UTF-8");
                    return headers;
                }

            };

            if (!SharedPreUtils.getString(getApplication(), "user_tel", "").equals("")) {
                volleySingleton.addQueue(request, "insertHistory");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
